<template>
  <section v-show="showMemberListModal" @click.self="closeMemberModal" class="my-modal-page">
    <div class="page-content c-text-hidden">
      <div class="cap c-p c-pt18 c-pb18 c-bd-b1 c-pl24 c-pr24  c-bg-white">
        <div class="c-fc-xblack c-fw600 c-fs28 c-textAlign-c">群成员</div>
        <span class="iconfont c-fs24 c-fc-gray c-ml20 c-pa c-p-r20 c-p-tp50 c-translate-y-50" @click="closeMemberModal">&#xeca0;</span>
      </div>
      <div id="scrollMemberList" @scroll="onMemberScroll" class="c-content-scroll c-hh800">
        <section class="c-flex-row c-aligni-center c-pv14">
          <new-search-bar class="c-flex-grow1 c-w0" :placeholder="placeholdText" @search='startSearch' @cancel='searchCancel' :searchText='nickname'></new-search-bar>
        </section>
        <div v-if="typeBar!=-2">
          <div class="c-flex-row c-justify-sb">
            <div class="c-ph24 c-fs22 c-fc-sblack c-pb34">
              管理员、讲师{{hasGuestMember ? '、嘉宾':''}}（{{teaMerberList.length}}人）
            </div>
            <div class="c-fs22 c-fc-sblack c-ph24 c-pt20" v-show="showOline">当前在线人数：{{onlineCount}}</div>
          </div>
          <div class="c-pb30 c-flex-row c-ph24 c-aligni-center" v-for="(item) in teaMerberList" :key="item.userId">
            <div class="c-hh68 c-ww68 c-text-hidden c-bd1 c-brp50">
              <img v-lazy="item.avatar" alt="" :key="item.avatar" />
            </div>
            <div class="c-ph20 c-fs26  c-fc-xblack c-flex-grow1 c-w0">
              {{item.dynamicName || item.realName || item.userName}}
            </div>
            <div>
              <div v-if="item.role==2" :class="item.subRole==1 ? 'role-guest':'role-teacher'">{{item.tag}}</div>
              <div v-if="item.role==4" class="role-admin">管</div>
              <div v-if="item.role==6"><span  :class="item.subRole==1 ? 'role-guest':'role-teacher'">{{item.tag}}</span></div>
            </div>
          </div>
          <div class="c-hh20 c-bg-sgray"></div>
          <my-small-tabbar :tbaIconBg="'c-bg-xblue'" :tabList="tabList" :tabIndex="typeBar" @changeTab="changeType" class="c-mb16" :tabNameClass="fontSize" :fontSet="fontSet"></my-small-tabbar>
        </div>
        <!-- <div class="c-ph24 c-pt24 c-fs24 c-pb40 c-flex-row c-justify-sb c-aligni-center">
      <span class="c-fc-sblack">普通成员（{{totalMemberNum}}人）</span>
      <span class="c-fc-gray" v-show="userRole == 4 || userRole == 6">禁言设置</span>
    </div> -->

        <div class="c-pb30 c-flex-row c-ph24 c-aligni-center c-justify-sb" v-for="(item, index) in memberList" :key="index">
          <div class="c-flex-row c-aligni-center">
            <div class="c-hh68 c-ww68 c-text-hidden c-bd1 c-brp50">
              <img :src="$addXossFilter(item.avatar)" alt="" />
            </div>
            <div class="c-ph20 c-fs26">
              {{ item.dynamicName || item.realName || item.userName || '' | hiddenLiveUserName(isHideUserName)}}
            </div>
          </div>
          <div class="c-aligni-center c-justify-sb c-flex-row" v-if="(userRole == 4 || userRole == 6)&&item.status=='-5'">
            <div class="c-ww102 c-lh40 c-hh40 c-br20 c-fs20 c-textAlign-c theme-fc c-bg-f2" @click="Rejoin(item,0)">加群</div>
          </div>
          <div class="c-aligni-center c-justify-sb c-flex-row" v-if="(userRole == 4 || userRole == 6)&&item.status=='-3'">
            <div class="c-ww102 c-lh40 c-hh40 c-br20 c-fs20 c-textAlign-c theme-fc c-bg-f2" @click="Rejoin(item,1)">移出</div>
          </div>
          <div class="c-aligni-center c-justify-sb c-flex-row c-p" v-else-if="(userRole == 4 || userRole == 6)&&item.status!='-3'&&item.status!='-5'">
            <!-- <x-switch title="" :value-map="[1, -2]" prevent-default v-model="item.status" @on-click="forbiddenTalk(item, index)" class="c-ph0"></x-switch> -->
            <div class="iconfont c-fs32 c-fc-gray c-mr30 c-inlineblack" @click="forbiddenTalk(item, index)">{{item.status==1?'&#xe639;':'&#xe63b;'}}</div>
            <opera-tion :user='item' :socialRoomId='socialRoomId' @getMemberList='getMemberList' @operaFlagChange='operaFlagChange' :operaFlag='operaFlag'></opera-tion>
          </div>
        </div>
        <loading-status-tem :dataStatus="dataStatus" noDataText="没有成员"></loading-status-tem>
        <!-- <div class="c-fc-sxblack c-fs20 c-textAlign-c c-pv20" v-show="dataStatus == 'LOADING'">{{'加载中...'}}</div> -->
        <section class="c-flex-row c-ph24 c-aligni-center c-justify-sb c-bd-t1 c-hh88 c-pf c-p-b0 c-w100 c-maxw640 c-bg-white c-pz1 mb5_default">
          <!-- <div class="c-flex-grow1 c-w0 c-flex-row c-aligni-center c-justify-end"> -->
          <!-- <div class="c-w100 c-flex-row c-flex-center"> -->
          <div class="c-bg-xblue c-fc-white c-flex-row c-lh c-flex-grow1 c-flex-center c-hh64 c-br36 c-fs24" @click="clickShowShare">
            邀请好友
          </div>
          <!-- </div> -->
          <!-- </div> -->
        </section>
      </div>
    <!-- <div @click="clickShowShare" class="c-pf c-p-b0 c-maxw640 c-hh80 c-lh80 theme-bg c-fc-white c-fs32 c-w100 c-textAlign-c">
      邀好友加群
    </div> -->
    </div>
  </section>

</template>

<script>
import newSearchBar from "@/components/templates/common/newSearchBar.vue"
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import operaTion from "@/components/templates/social/operaTion.vue";
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import { utilJs } from "@/utils/common.js";
let pageIndex = 1;
export default {
  inject:['provideGetDynamicName'],
  components: {
    newSearchBar,
    MySmallTabbar,
    operaTion,
    loadingStatusTem
  },
  props: {
    socialRoomId: {
      type: String,
      default: '',
    },
    detailId: {
      type: Number,
      default: 0,
    },
    teaMerberList: {
      type: Array,
      default: () => {
        return []
      },
    },
    showMemberListModal: {
      type: Boolean,
      default: false
    },
    userRole: {
      type: Number,
      default: 1
    },
    isHideUserName: {
      type: Boolean,
      default: false
    },
    showOline:{
      type: Boolean,
      default: false
    }
  },
  watch: {
    showMemberListModal(val) {
      if (val) {
        this.isMobile = utilJs.isMobileUserAgent();
        pageIndex = 1;
        this.dataStatus = 'HAS_MORE_DATA';
        this.memberList = [];
        this.getMemberList();
        this._getSrmOnlineCount(this.socialRoomId);
        this.hasGuestMember = this.teaMerberList.some(i => i.subRole == 1 && i.role == 2);
      } else {
        this.searchCancel()
      }
    },
    teaMerberList(val) {
      if (this.provideGetDynamicName) {
        val.forEach(item => {
          item = this.provideGetDynamicName(item);
        })
      }
    }
  },
  data() {
    return {
      placeholdText: '搜索学员',
      theme: localStorage.getItem("colorName") || 'mb5_default',
      dataStatus: 'HAS_MORE_DATA',
      totalMemberNum: 0,
      memberList: [],
      nickname: '',
      hasGuestMember: false,
      tabList: [],
      typeBar: 0,
      black: 0,
      normal: 0,
      remove: 0,
      fontSet: {
        defaultColor: 'c-fc-sblack',
      },
      fontSize: 'c-fs22',
      operaFlag: false,
      isMobile: true,
      onlineCount:0, //在线人数
    };
  },
  methods: {
    closeMemberModal() {
      this.$emit("update:showMemberListModal", false);
    },
    operaFlagChange() {
      this.operaFlag = !this.operaFlag
    },
    onMemberScroll() {
      let domScroll = document.getElementById('scrollMemberList');
      if (this.checkScrollBottom(domScroll) && this.dataStatus == 'HAS_MORE_DATA') {
        this.getMemberList();
      }
    },
    //是否滚到底部
    checkScrollBottom(curDom) {
      if (curDom.scrollTop + curDom.clientHeight >= curDom.scrollHeight - 5) {
        return true;
      } else {
        return false;
      }
    },
    //改变typeBar
    changeType(type) {
      if (this.typeBar != type) {
        this.typeBar = type;
      }
      this.memberList = []
      pageIndex = 1
      this.getMemberList()
      return false;
    },
    //获取不同类型成员数量
    getRoomMemberCount() {
      utilJs.getMethod(`${global.apiurl}social/getRoomMemberCount/${this.socialRoomId}?detailId=${this.detailId}`, res => {
        this.black = res.black
        this.normal = res.normal
        this.remove = res.remove
        if (this.userRole == 4 || this.userRole == 6) {
          this.tabList = []
          this.tabList = [{
            title: '普通成员 (' + this.normal + '人)',
            index: 0,
          }, {
            title: '移出社群 (' + this.remove + '人)',
            index: 1,
          }, {
            title: '黑名单 (' + this.black + '人)',
            index: 2,
          }]
        } else {
          this.tabList = [{
            title: '普通成员(' + this.normal + '人)',
            index: 0,
          }]
        }
      })
    },
    //获取群成员列表
    getMemberList() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(`${global.apiurl}social/socialMember/${this.socialRoomId}?detailId=${this.detailId}&page=${pageIndex}&limit=20&nickname=${this.nickname}&type=${this.typeBar + 1}`, res => {
        if (this.provideGetDynamicName) {
          res.data.forEach(item => {
            item = this.provideGetDynamicName(item);
          })
        }
        if (pageIndex == 1) {
          this.memberList = res.data;
        } else {
          this.memberList = [...this.memberList, ...res.data];
        }
        this.getRoomMemberCount()
        if (res.data && (res.data.length < 20)) {
          this.dataStatus = pageIndex == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
        } else {
          this.dataStatus = 'HAS_MORE_DATA';
          pageIndex++;
        }
        // this.totalMemberNum = res.total * 1;
        // if (res.to * 1 == res.total * 1) {
        //   this.dataStatus = res.total * 1 == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
        // } else {
        //   this.dataStatus = 'HAS_MORE_DATA';
        //   pageIndex++;
        // }
      }
      );
    },
    //获取在线人数
    _getSrmOnlineCount:function(roomID) {
      utilJs.getMethod(`${global.apiurl}appletLiveVideo/getSrmOnlineCount/${roomID}`, res => {
        this.onlineCount = res.onlineNum;
      })
    },
    clickShowShare() {
      this.$emit('clickShowShare');
    },
    forbiddenTalk(user, index) {
      let s = (user.status == -2) ? 1 : -2;
      utilJs.postMethod(
        global.apiurl + `social/forbiddenTalk/${user.srmId}`, { "socialRoomId": this.socialRoomId, "status": s },
        res => {
          //-3：被删除 -2: 禁言状态, 1为正常状态，2验证密码才能进入群
          user.status = s;
          Vue.set(this.memberList, index, user);
          let msg = s == 1 ? ' 已解除禁言' : (s == -2 ? ' 已被禁言' : '');
          this.$showCjToast({
            text: user.userName + msg,
            type: "success",
            time: 1000
          });
        },
        failRes => {}
      );
    },
    // 重新加入
    Rejoin(user, status) {
      let $this = this
      $this.operation = false
      $this.$cjConfirm({
        title: '提示',
        titleCenter: true, //标题是否居中
        message: status == 1 ? '学员移出黑名单后将享有使用社群的权限。确定将 ' + user.userName + ' 移出黑名单吗?'
        : '学员重新进群后重新享有使用社群的权限。确定将 ' + user.userName + ' 重新加入社群吗?', //弹窗内容
        messageCenter: true, //内容是否居中
        showMasker: true, //是否显示透明背景
        clickCloseModal: false, //是否点击透明背景关闭弹窗
        showCancelButton: true, //是否显示取消按钮
        cancelButtonText: '', //取消按钮文本
        confirmButtonText: '', //确认按钮文本
        onConfirm() {
          utilJs.postMethod(
            global.apiurl + `social/reJoinMember/${user.srmId}`, { "socialRoomId": $this.socialRoomId },
            res => {
              let msg = status == 1 ? '移出黑名单成功' : (status == 0 ? '加群成功' : '');
              $this.$showCjToast({
                text: msg,
                type: "success",
                time: 1000
              });
              $this.getMemberList()
            },
            failRes => {}
          );
        }, //确认事件回调
        onCancel: null, //取消事件回调
      })
    },
    //开始搜索
    startSearch(searchText) {
      this.nickname = searchText.searchValue;
      pageIndex = 1;
      console.log(this.nickname)
      this.memberList = []
      this.typeBar = -2
      this.getMemberList();
    },
    searchCancel() {
      this.nickname = ''
      pageIndex = 1;
      this.memberList = []
      this.typeBar = 0
      console.log(this.nickname)
      this.getMemberList();
    }
  },
  deactivated() {
    console.log('成员关闭')
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.my-modal-page {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  margin: auto;
  z-index: 2018;
  width: 100%;
  max-width: 16rem;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
}
.page-content {
  /* overflow-y: auto;
  overflow-x: hidden; */
  width: 100%;
  /* height: 90%; */
  /* padding-top: 0.5rem; */
  border-radius: 0.5rem 0.5rem 0 0;
  -webkit-overflow-scrolling: touch;
  background-color: #ffffff;
}
.role-teacher,
.role-admin,
.role-guest
{
  padding: 0 0.15rem;
  height: .6rem;
  line-height:.6rem;
  overflow: hidden;
  display: inline-block;
  border-radius:.15rem;
  color: #fff;
  font-size:.4rem;
}

.role-teacher,.role-guest{
  background: #2194ff;
}
.role-admin {
  background: #2194ff;
}
.c-pv14 {
    padding-top: 0.35rem;
    padding-bottom: 0.35rem;
}
</style>
